//
//  VersionManager.m
//  SWCommonFrame
//
//  Created by shaowei on 13-6-18.
//  Copyright (c) 2013年 shaowei. All rights reserved.
//

#import "VersionCheck.h"

@interface VersionCheckModel:NSObject

@property (nonatomic,assign) CGFloat netVersion;
@property (nonatomic,assign) CGFloat currentVersion;
@property (nonatomic,assign) BOOL checkResult;
@property (nonatomic,assign) BOOL isNeedUpdate;

@end

@implementation VersionCheckModel

@end

#define LAST_CHECK_DATE @"lastCheckUpdateDate"
#define FORBIDED_VERSION_NUMBER @"forbided_version_number"

@interface VersionCheck()

@property (nonatomic, strong) NSString *appID;
@property (nonatomic, strong) VersionCheckModel *model;
@property (nonatomic, assign) CGFloat intervalTime;

@end

@implementation VersionCheck

+ (instancetype)sharedInstance{
    static VersionCheck *sInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[[self class] alloc] init];
        sInstance.intervalTime = 1;
    });
    
    return sInstance;
}

#pragma mark - Function - Public

+ (void)setAppID:(NSString *)appID{
    if (appID) {
        [[self sharedInstance] setAppID:appID];
    }
}

+ (void)setUpdateIntervalTime:(CGFloat)intervalTime{
    [[self sharedInstance] setIntervalTime:intervalTime];
}

+ (void)checkUpdateIsNeedDefaultPrompt:(BOOL)isNeed complete:(VersionCheckComplete)complete{
    NSString *appID = [[self sharedInstance] appID];
    if (!appID.length) {
        NSAssert(0, @"请设置需要更新的appID");
    }
    
    NSString *urlStr = [self getAppUpdateURLStringWithID:appID];
    [self netRequestWithURLString:urlStr
                completionHandler:^(BOOL isSucceed, NSString *responseStr, NSError *error) {
                    CGFloat currentVersion = [VersionCheck getAppVersionNumber];
                    VersionCheckModel *model = [VersionCheck appUpdateDataParse:responseStr];
                    BOOL checkResult = isSucceed && model.checkResult;
                    BOOL isNeedUpdate = NO;
                    if (checkResult) {
                        //检测结果返回成功，则更新本地的更新记录
                        [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970]
                                                                  forKey:LAST_CHECK_DATE];
                        isNeedUpdate = (model.netVersion - currentVersion) > 0.001f;
                    }
                    
                    model.currentVersion = currentVersion;
                    model.isNeedUpdate = isNeedUpdate;
                    [[VersionCheck sharedInstance] setModel:model];
                    if (isNeedUpdate) {
                        [VersionCheck showPromptWithModel:model];
                    }
                    
                    complete(checkResult, isNeedUpdate, currentVersion, model.netVersion);
                }];
}

+ (void)forbidPromptInVersion:(CGFloat)versionNum{
    [[NSUserDefaults standardUserDefaults] setDouble:versionNum forKey:FORBIDED_VERSION_NUMBER];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (CGFloat)getAppVersionNumber{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    return [version floatValue];
}

+ (BOOL)isNeedCheckUpdate{
    NSTimeInterval lastCheckTime = [[NSUserDefaults standardUserDefaults] doubleForKey:LAST_CHECK_DATE];
    
    //检测本地是否有更新记录
    if ((lastCheckTime - 0) > 1) {
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
        NSTimeInterval intervalTime = [[self sharedInstance] intervalTime] *24*60*60;
        BOOL isOverTime = (nowTime - lastCheckTime) > intervalTime;
        
        return isOverTime;
    }else{
        //还没有检测更新过
        return YES;
    }
    
}

#pragma mark Function - Private

+ (VersionCheckModel *)appUpdateDataParse:(NSString *)responseStr{
    
    NSString *resPattern = @"(?<=\"version\":\")[^\"]+";
    NSRegularExpression *regularTmp = [NSRegularExpression regularExpressionWithPattern:resPattern
                                                                                options:NSRegularExpressionCaseInsensitive
                                                                                  error:nil];
    NSRange matchRange = [regularTmp rangeOfFirstMatchInString:responseStr
                                                       options:0
                                                         range:NSMakeRange(0, [responseStr length])];
    
    VersionCheckModel *model = [[VersionCheckModel alloc] init];
    if (matchRange.length > 0) {
        model.checkResult = YES;
        model.netVersion = [[responseStr substringWithRange:matchRange] doubleValue];
    }else{
        model.checkResult = NO;
    }
    
    return model;
}

+ (BOOL)isForbidedPromptWithVersionNum:(CGFloat)versionNum{
    CGFloat storedNum = [[NSUserDefaults standardUserDefaults] doubleForKey:FORBIDED_VERSION_NUMBER];
    return fabs(versionNum - storedNum) < 0.001f;
}

+ (NSString *)getAppUpdateURLStringWithID:(NSString *)appID{
    NSString *baseURLStr = APP_UPDATE_URL;
    if (appID) {
        return [baseURLStr stringByAppendingString:appID];
    }else{
        return nil;
    }
}

+ (NSString *)getAppURLStringWithID:(NSString *)appID{
    NSString *baseURLStr = APP_GET_URL;
    if (appID) {
        return [baseURLStr stringByAppendingString:appID];
    }else{
        return nil;
    }
}

+ (void)showPromptWithModel:(VersionCheckModel *)model{
    NSString *title = nil;
    NSString *content = nil;
    NSString *buttonTitle = @"确定";
    BOOL isShowPrompt = YES;
    if (model.checkResult) {
        if (model.isNeedUpdate) {
            title = SWString(@"有新版本 %.1f",model.netVersion);
            content = SWString(@"您当前的版本为 %.1f",model.currentVersion);
            buttonTitle = @"取消";
            if ([self isForbidedPromptWithVersionNum:model.netVersion]) {
                isShowPrompt = NO;
            }
        }else{
            title = SWString(@"您当前版本 %.1f 为最新版",model.currentVersion);
        }
    }else{
        title = @"版本检测失败";
    }
    
    if (isShowPrompt) {
        //回到前台主线程执行
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:title
                                                         message:content
                                                        delegate:[VersionCheck sharedInstance]
                                               cancelButtonTitle:buttonTitle
                                               otherButtonTitles: nil];
            [av addButtonWithTitle:@"去更新"];
            [av addButtonWithTitle:@"忽略此版本"];
            av.tag = 1;
            [av show];
        }) ;
    }
    
    
}

+ (void)openAppStoreWithURL:(NSString *)appUrlStr{
    NSURL *url = [NSURL URLWithString:appUrlStr];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }else{
        ALERT_VIEW(@"无法更新app", nil);
    }
    
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            //go update
            NSString *urlStr = [VersionCheck getAppURLStringWithID:[[VersionCheck sharedInstance] appID]];
            [VersionCheck openAppStoreWithURL:urlStr];
        }else{
            //ignore
            [VersionCheck forbidPromptInVersion:[[VersionCheck sharedInstance] model].netVersion];
        }
        
    }
}

#pragma mark - Net

+ (void)netRequestWithURLString:(NSString *)urlString completionHandler:(void (^)(BOOL, NSString*, NSError*))handler{
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:18];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               
                               NSString *responseStr = [[NSString alloc] initWithData:data
                                                                             encoding:NSUTF8StringEncoding];
                               handler(!connectionError, responseStr,connectionError);
                           }];
}





@end






